package network.TCP;

import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;

/**
 * Project ChatSystemG6 - INSA 4INFOA1 - 2013/2014
 * <P>
 * <li>Class ProgressBar : display the file transfer progression</li>
 * 
 * @author Christelle SIAGO HAPPI
 */

public class ProgressBar extends JFrame {

	private static final long serialVersionUID = 1L;
	public JPanel panel;
	public JProgressBar bar;
	private JLabel status;

	private long size;

	/**
	 * 
	 * @param size
	 *            : the size of the file
	 * @param isEmission
	 *            is true is the transfer is an emission and false otherwise
	 */
	public ProgressBar(long size, char isEmission) {

		super();
		setIconImage(new ImageIcon("/ressources/app.gif").getImage());

		this.size = size;
		panel = new JPanel(new BorderLayout());

		bar = new JProgressBar();
		bar.setMaximum((int) size);
		bar.setIndeterminate(false);
		bar.setStringPainted(true);

		status = new JLabel();

		if (isEmission == 'r')
			this.setTitle("File Reception ");
		else
			this.setTitle("File Emission");

		// Adding the panel title
		panel.add(status, BorderLayout.SOUTH);
		panel.add(bar, BorderLayout.CENTER);

		this.add(panel);
		this.setSize(320, 100);
		this.setVisible(true);

	}

	/**
	 * Update status
	 * 
	 * @param s
	 *            status message
	 */
	public void setStatus(String s) {
		status.setText(s);
	}

	/**
	 * thread Action
	 */
	public void setProgressBar(Speed speed) {

		long l = speed.getOctectProceed();

		// Update on progress
		bar.setValue((int) l);
		// Updating the transfer speed
		setStatus("Speed : " + getExactValue(speed.getSpeedValue()) + "/s"
				+ "                             Recu :"
				+ (getExactValue(l) + " / " + getExactValue(size)));
	}

	private String getExactValue(long value) {

		if (value >= 1024 * 1024 * 1024)
			return ""
					+ (value / 1024 / 1024 / 1024)
					+ "."
					+ (value / 1024 / 1024 - 1024 * (value / 1024 / 1024 / 1024))
					/ 100 + " Go";
		else if (value >= 1024 * 1024)
			return "" + (value / 1024 / 1024) + "."
					+ (value / 1024 - 1024 * (value / 1024 / 1024)) / 100
					+ " Mo";
		else if (value >= 1024)
			return "" + (value / 1024) + "." + (value - 1024 * (value / 1024))
					/ 100 + " Ko";
		return "" + value + " o";
	}
}
